package com.peakmain.wanandroid.mymodule.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.peakmain.baselibrary.dialog.AlertDialog;
import com.peakmain.baselibrary.navigationbar.DefaultNavigationBar;
import com.peakmain.baselibrary.utils.file.FileManager;
import com.peakmain.baselibrary.utils.file.FileUtil;
import com.peakmain.minemodule.R;
import com.peakmain.wanandroid.mymodule.adapter.ImagePreviewAdpater;
import com.peakmain.wanandroid.mymodule.base.BaseMineActivity;
import com.peakmain.wanandroid.mymodule.bean.Constant;
import com.peakmain.wanandroid.netmodule.net.http.download.DownloadListener;
import com.peakmain.wanandroid.netmodule.net.http.download.DownloadTask;
import com.peakmain.wanandroid.netmodule.utils.log.MaxLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * author ：Peakmain
 * createTime：2020/2/22
 * mail:2726449200@qq.com
 * describe：
 */
public class ImagePreviewActivity extends BaseMineActivity implements ViewPager.OnPageChangeListener {
    private ViewPager mViewPager;
    private ArrayList<String> mImageList;
    private int position;
    private ImagePreviewAdpater mImagePreviewAdpater;
    private DefaultNavigationBar mDefaultNavigationBar;
    private DownloadTask mDownloadTask;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_image_preview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView() {
        setTitle();

        mViewPager = findViewById(R.id.view_pager);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mImageList = bundle.getStringArrayList(Constant.DATA);
            position = bundle.getInt(Constant.POSITION, 0);
        }
        mViewPager.addOnPageChangeListener(this);
        mImagePreviewAdpater = new ImagePreviewAdpater(this, mImageList);
        mViewPager.setAdapter(mImagePreviewAdpater);
        if (position > 0) {
            mViewPager.setCurrentItem(position);
        }
        setImageTitle(position);
        mImagePreviewAdpater.setOnPreviewImageLongClick(view -> {
            showSaveOrForwardDialog();
        });
    }

    private void showSaveOrForwardDialog() {
        AlertDialog dialog = new AlertDialog.Builder(ImagePreviewActivity.this)
                .setContentView(R.layout.dialog_show_image_deal)
                .fromButtom(true)
                .setFullWidth()
                .show();
        dialog.setOnClickListener(R.id.tv_cancel, v -> {
            dialog.cancel();
        });
        //转发
        dialog.setOnClickListener(R.id.tv_forword, v -> {
            //预留
            ToastUtils.showShort("转发");
        });
        dialog.setOnClickListener(R.id.tv_save_image, v -> {
            saveImage(dialog);
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void saveImage(AlertDialog dialog) {
        String photoFileName = FileUtil.getPhotoFileName();
        String saveFile = FileManager.getInstance().getImagePath()+photoFileName;
        if (!haveReadAndWritePerm()) {
            requestReadAndWritePerm();
        }else{
            DownloadListener downloadListener = new DownloadListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onProgress(int progress) {
                    MaxLog.e("TAG", "下载进度" + progress);
                }

                @Override
                public void onError() {
                    dialog.cancel();
                    ToastUtils.showLong("保存失败");
                    MaxLog.e("TAG", "下载错误");

                }

                @Override
                public void onFinish(File targetFile) {
                    dialog.cancel();
                    ToastUtils.showLong("保存成功");
                    try {
                        MediaStore.Images.Media.insertImage(getContentResolver(), saveFile, photoFileName, "peakmain");//插入图库
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + targetFile.getAbsolutePath())));//更新图库
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    MaxLog.e("TAG", "下载完成" + targetFile.getAbsolutePath());

                }
            };
            if (mDownloadTask == null) {
                mDownloadTask = new DownloadTask(mImageList.get(position), FileUtil.getFileByPath(saveFile), downloadListener);
            }
            mDownloadTask.start();
        }

    }

    //设置NavigationBar
    private void setTitle() {
        mDefaultNavigationBar = new DefaultNavigationBar
                .Builder(this, (ViewGroup) findViewById(android.R.id.content))
                //是否显示返回按钮
                .setDisplayHomeAsUpEnabled(true)
                //设置返回按钮的点击事件
                .setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                })
                .hideRightView()
                .create();
    }

    //设置标题
    private void setImageTitle(int position) {
        List<String> imageList = mImagePreviewAdpater.getImageList();
        if (imageList != null && !imageList.isEmpty()) {
            mDefaultNavigationBar.setTitleText(position + 1 + "/" + imageList.size());
        }
    }


    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        setImageTitle(i);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }
}
